package edu.zut.main.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketDemo2 {

}
/**
 * web中，文件上传操作：基于浏览器访问本地文件上传到服务器
 * 浏览器：客户端 ----> 读取本地文件将其上传到服务器
 * 服务器： 将客户端发送过来的文件保存到服务器的磁盘上
 *
 * 改写：结合多线程   模拟多客户端同时上传文件到服务器
 *
 */

class FileClient{

    public static void main(String[] args) throws IOException {

        Socket socket = new Socket("127.0.0.1", 8888);
        System.out.println("连接成功.....");
        //本地的输入流
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("C:\\Users\\xueyin\\Desktop\\Redis.docx")));
        //基于socket输出流
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());

        byte[] buffer = new byte[521];
        int len;
        while ((len = bis.read(buffer))!= -1){
            bos.write(buffer,0,len);
        }
        bos.flush();

        socket.shutdownOutput();

        //接收服务器返回的结果
        InputStream is = socket.getInputStream();
        byte[] bytes = new byte[521];
        int i;
        while ((i=is.read(bytes)) != -1){
            System.out.println(new String(bytes,0,i));
        }
        is.close();
        bos.close();
        bis.close();
        socket.close();

    }

}

class FileServer{
    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("等待连接......");
        Socket socket = serverSocket.accept();
        System.out.println("连接就绪，准备接收文件......");

        InputStream is = socket.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);

        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("./redis.docx")));


        int len;
        byte[] bytes = new byte[521];
        //一面读取客户端上传的数据，一面将其保存到磁盘
        while ((len = is.read(bytes)) != -1){
            bos.write(bytes,0,len);
        }
        bos.flush();

        socket.shutdownInput();

        OutputStream os = socket.getOutputStream();
        os.write("上传文件成功".getBytes());

        os.close();
        bos.close();
        bis.close();
        socket.close();
        serverSocket.close();



    }
}
